require([
    'jquery',
    'module/util',
    'global',
    'underscore',
    'jquery.chosen',
    'ckeditor',
	'requirejs/domready!'],
function($, util, g, _) {
	
	var saving = false;
	
	$("#edit-role-modal select").chosen({
		width: "100%",
		no_results_text: "没有发现记录匹配"
	});
	
	$('#edit-role-modal').on('show.bs.modal', function(){
		var obj = $(this).data('obj');
		if(!obj){
			$(this).find('.modal-header .action').text('添加');
			$(this).find('input[name="roleName"]').prop('disabled', false);
			saving = true;
		}else{
			$(this).find('.modal-header .action').text('编辑');
			$(this).find('input[name="roleName"]').prop('disabled', true);
			saving = false;
		}
		obj = obj || {};
		$(this).find('form input, form select').each(function(){
			var p = $(this).data('prop') || $(this).attr('name');
			if(p){
				var ks = p.split('\.');
				var v = obj;
				_.each(ks, function(k){
					v ? v = v[k] : v = null;
				});
				$(this).val(v);
			}
		});
		$(this).find('form select').trigger("chosen:updated");
	}).on('click', '.btn-primary', function(){
		var dto = {};
		$('#edit-role-modal').find('form input, form select').each(function(){
			if($(this).attr('name')){
				dto[$(this).attr('name')] = $(this).val();
			}
		});
		dto.saving = saving;
		$.ajax({
		  type: 'post',
		  dataType: 'json',
		  url: g.context+ '/admin/role',
		  data: JSON.stringify(dto),
		  contentType: 'application/json; charset=utf-8',
		  headers:{
			  'x-form-id': 'edit-role-modal'
		  }
	    }).done(function(result){
	    	if(result.code == 'ACK'){
		    	$('#edit-role-modal').modal('hide');
		    	$(window).trigger('ok.xt.modal', ['#edit-role-modal']);
	    	}
	    });
	});
});